#!/bin/bash

# 水文预报 WebSocket 服务 Docker 启动脚本
# 作者：Gaoyu <gaoyu.ssdut@icloud.com>
#
# 使用方法：
#   bash scripts/start_websocket_docker.sh         # HTTP 模式
#   bash scripts/start_websocket_docker.sh ssl     # HTTPS 模式

set -e

# 检查是否启用 SSL
SSL_MODE=${1:-""}
if [ "$SSL_MODE" = "ssl" ]; then
    echo "🚀 启动水文预报 WebSocket 服务（Docker + SSL 版本）..."
else
    echo "🚀 启动水文预报 WebSocket 服务（Docker 版本）..."
fi
echo "=============================================="

# 检查 .env 文件
if [ ! -f ".env" ]; then
    echo "⚠️  .env 文件不存在，从示例文件创建..."
    if [ -f ".env.example" ]; then
        cp .env.example .env
        echo "✅ 已从 .env.example 创建 .env 文件"
        echo "📝 注意：VLLM_BASE_URL 已设置为 http://10.48.0.81:8000/v1"
    else
        echo "❌ 错误：.env.example 文件不存在"
        exit 1
    fi
fi

# 显示配置
echo ""
echo "📋 当前配置:"
grep -v "^#" .env | grep -v "^$" || true
echo ""

# 设置变量
IMAGE_NAME="vllm-websocket-server"
CONTAINER_NAME="websocket-server"
WEBSOCKET_PORT=$(grep WEBSOCKET_PORT .env | cut -d '=' -f2 || echo "8765")

# 检查容器是否已运行
if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then
    echo "⚠️  容器 $CONTAINER_NAME 已在运行"
    echo "🔄 停止现有容器..."
    docker stop $CONTAINER_NAME
    docker rm $CONTAINER_NAME
fi

# 检查容器是否存在但未运行
if [ "$(docker ps -aq -f name=$CONTAINER_NAME)" ]; then
    echo "🗑️  删除已停止的容器..."
    docker rm $CONTAINER_NAME
fi

# 构建镜像
echo ""
echo "🔨 构建 Docker 镜像..."
docker build -f docker/Dockerfile.websocket -t $IMAGE_NAME .

if [ $? -ne 0 ]; then
    echo "❌ Docker 镜像构建失败"
    exit 1
fi

echo "✅ Docker 镜像构建成功"

# 启动容器
echo ""
echo "🚀 启动容器..."

# SSL 配置
if [ "$SSL_MODE" = "ssl" ]; then
    echo "🔒 启用 SSL 模式"
    
    # 检查 SSL 证书
    if [ ! -f "/etc/letsencrypt/live/ws.waterism.tech/fullchain.pem" ]; then
        echo "❌ 错误: SSL 证书不存在"
        echo "   证书路径: /etc/letsencrypt/live/ws.waterism.tech/"
        exit 1
    fi
    
    echo "✅ SSL 证书已找到"
    
    # 启动容器（SSL 模式）
    docker run -d \
        --name $CONTAINER_NAME \
        --network host \
        --env-file .env \
        -e SSL_ENABLED=true \
        -e SSL_CERTFILE=/etc/letsencrypt/live/ws.waterism.tech/fullchain.pem \
        -e SSL_KEYFILE=/etc/letsencrypt/live/ws.waterism.tech/privkey.pem \
        -v /etc/letsencrypt:/etc/letsencrypt:ro \
        --restart unless-stopped \
        $IMAGE_NAME
else
    # 启动容器（HTTP 模式）
    docker run -d \
        --name $CONTAINER_NAME \
        --network host \
        --env-file .env \
        --restart unless-stopped \
        $IMAGE_NAME
fi

if [ $? -ne 0 ]; then
    echo "❌ 容器启动失败"
    exit 1
fi

echo ""
echo "=============================================="
echo "✅ WebSocket 服务已启动！"
echo ""
echo "📡 服务信息:"
if [ "$SSL_MODE" = "ssl" ]; then
    echo "   - 模式: HTTPS + WebSocket Secure (WSS)"
    echo "   - WebSocket: wss://localhost:$WEBSOCKET_PORT/ws"
    echo "   - HTTP API: https://localhost:$WEBSOCKET_PORT/api/execute"
    echo "   - 健康检查: https://localhost:$WEBSOCKET_PORT/api/health"
    echo "   - API 文档: https://localhost:$WEBSOCKET_PORT/docs"
else
    echo "   - 模式: HTTP + WebSocket"
    echo "   - WebSocket: ws://localhost:$WEBSOCKET_PORT/ws"
    echo "   - HTTP API: http://localhost:$WEBSOCKET_PORT/api/execute"
    echo "   - 健康检查: http://localhost:$WEBSOCKET_PORT/api/health"
    echo "   - API 文档: http://localhost:$WEBSOCKET_PORT/docs"
fi
echo "   - 容器名称: $CONTAINER_NAME"
echo "   - 镜像名称: $IMAGE_NAME"
echo ""
echo "📝 常用命令:"
echo "   - 查看日志: docker logs -f $CONTAINER_NAME"
echo "   - 停止服务: docker stop $CONTAINER_NAME"
echo "   - 重启服务: docker restart $CONTAINER_NAME"
echo "   - 删除容器: docker rm -f $CONTAINER_NAME"
if [ "$SSL_MODE" = "ssl" ]; then
    echo "   - 测试服务: curl -k https://localhost:$WEBSOCKET_PORT/api/health"
else
    echo "   - 测试服务: curl http://localhost:$WEBSOCKET_PORT/api/health"
fi
echo ""
echo "🔍 查看实时日志中..."
echo "=============================================="
echo ""

# 显示日志
docker logs -f $CONTAINER_NAME

